package com.zhangqiancheng.wcdmaconsole;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.ProtocalAndUdp.FileOpenerDialog;
import com.ProtocalAndUdp.MyDialogListener;
import com.zhangqiancheng.wcdmaconsole.db.DbHelper;

public class DatashowActivity extends Activity implements MyDialogListener {

	DbHelper dbTable = null;
	SQLiteDatabase db;
	Map<String, Object> item;
	ArrayList<Map<String, Object>> data;
	// List<Map<String, Object>> allData = new ArrayList<Map<String, Object>>();
	SimpleAdapter listAdapter;
	ListView listview;
	// private int startIndex = 0;
	private int currentPage = 1;
	private int sizePerPage = 15;
	private int totalSize = 0;
	private boolean done = false;
	private View footerView;
	private TextView tvCount;
	private String selection;
	private String[] selectionArgs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_datashow);
		listview = (ListView) findViewById(R.id.listView1);
		tvCount = (TextView) findViewById(R.id.TVCount);
		footerView = getLayoutInflater().inflate(R.layout.datashow_list_footer, null);
		listview.addFooterView(footerView);
		
		

		Button loadMoreButton = (Button) findViewById(R.id.btnLoadMore);
		loadMoreButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				loadMoreData();

			}
		});
		
		db = DbHelper.getInstance(this, DbHelper.DATABASE_NAME, null, DbHelper.DATABASE_VERSION)
				.getReadableDatabase();
		totalSize = findTotalSize();

		data = new ArrayList<Map<String, Object>>();
		listAdapter = new SimpleAdapter(this, data, R.layout.datashow_list_item,
				new String[] { "imsi", "imei", "note", "time" },
				new int[] { R.id.tvItemIMSI, R.id.tvItemIMEI, R.id.tvItemNote, R.id.tvItemTime });
		listview.setAdapter(listAdapter);

		// DbHelper.insertDemo(this);

		// 加载数据
		dbSelect();

		
		//tvCount.setText("共计：" + totalSize);
		// 注册查询事件
		Button btselect = ((Button) findViewById(R.id.btShow));
		btselect.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				noteSelectItem();
			}
		});
	}

	protected void loadMoreData() {

		if (!done) {
			currentPage++;
			dbSelect();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.datashow, menu);
		return true;
	}

	// 查询listview中的记录，如果存在，则标红（先将之前的标红记录恢复，再标红）
	private void noteSelectItem() {
		
		String imsi = ((TextView)findViewById(R.id.IMSI)).getText().toString();
		String imei = ((TextView)findViewById(R.id.etIMEI)).getText().toString();
		
		if (imsi.trim().length() > 0 && imei.trim().length() > 0)
		{
			selection = "imsi like ? and imei like ?";
			selectionArgs = new String[]{"%"+imsi+"%", "%"+imei+"%"};
		} else if (imsi.trim().length() > 0) {
			selection = "imsi like ?";
			selectionArgs = new String[]{"%"+imsi+"%"};
		} else if (imei.trim().length() > 0) {
			selection = "imei like ?";
			selectionArgs = new String[]{"%"+imei+"%"};
		} else {
			selection = null;
			selectionArgs = null;
		}
		
		currentPage = 1;
		totalSize = findTotalSize();
		
		data.clear();
		
		dbSelect();
	}

	private int findTotalSize() {

		String sql = "SELECT COUNT(*) FROM " + DbHelper.WCDMA_TABLE;
		
		if (selection != null)
			sql += " WHERE " + selection;
		
		SQLiteStatement stmt = db.compileStatement(sql);
		
		if (selectionArgs != null)
		{
			for (int i = 0; i < selectionArgs.length; i++) {
				stmt.bindString(i+1, selectionArgs[i]);
			}
		}
		
		int result = (int) stmt.simpleQueryForLong();
		
		stmt.close();
		
		return result;
	}

	@SuppressLint("DefaultLocale")
	private void dbSelect() {

		String limit = String.format("%d,%d", (currentPage - 1) * sizePerPage, sizePerPage);

		Cursor cursor = db.query(DbHelper.WCDMA_TABLE, null, selection, selectionArgs, null, null,
				DbHelper.CREATED_TIME_DESC, limit);

		try {
			while (cursor.moveToNext()) {
				// int id = cursor.getInt(0);
				String imsi = cursor.getString(1);
				String imei = cursor.getString(2);
				String note = cursor.getString(3);
				String time = cursor.getString(4);
				addItemToData(imsi, imei, note, time);
			}
		}
		finally {
			cursor.close();
		}
		
		int count = cursor.getCount();
		if (count < sizePerPage)
			done = true;

		if (done)
			listview.removeFooterView(footerView);
		showList();
	}

	public void onClear(View view) {

		alert();
	}

	private void alert() {

		AlertDialog.Builder builder = new Builder(this);
		builder.setIcon(android.R.drawable.btn_star);
		builder.setTitle("警告");
		builder.setMessage("您确定清除信息吗？");
		android.content.DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {

				dbDelete();
			}
		};
		builder.setPositiveButton("是", listener);
		builder.setNegativeButton("否", null);
		builder.create().show();
	}

	public void OnBack(View view) {

		onBackPressed();
	}

	private void dbDelete() {

		int i = db.delete(DbHelper.WCDMA_TABLE, null, null);
		if (i > 0) {
			toast("数据清除成功！");
		}
		else {
			toast("数据清除失败！");
		}
	}

	private void toast(String message) {

		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
	}

	private void addItemToData(String IMSI, String IMEI, String note, String time) {

		item = new HashMap<String, Object>();
		item.put("imsi", IMSI);
		item.put("imei", IMEI);
		item.put("note", note);
		item.put("time", time);
		data.add(item);
	}

	private void showList() {

		listAdapter.notifyDataSetChanged();
		
		tvCount.setText("共计 " + totalSize + " 条记录，显示 " + data.size() + " 条");
	}

	public void onExportClick(View view) {

		// 弹出保存对话框
		String path = null;
		FileOpenerDialog dlg =
				new FileOpenerDialog(
						DatashowActivity.this, 2, new String[] { "txt" }, path,
						DatashowActivity.this);
		dlg.setTitle("保存");
		dlg.show();
	}

	@Override
	public void OnOkClick(String path) {

		// TODO Auto-generated method stub
		// XlsOperate xls=new XlsOperate();
		// xls.createXLS(path);
		// int cols=2;
		// int rows=2;
		// for(int i=1;i<=cols;i++){
		// for(int j=1;j<=rows;j++){
		// xls.addData(0, i, j, "1");
		// }
		// }

	}
}
